<template>
  <div class="app-container">
    <el-card>
      <div class="card-header">
        <div class="title">订单流程跟踪</div>
        <div class="right">
          <el-button type="primary" size="small" @click="goBack">返回列表</el-button>
          <el-button type="success" size="small" @click="refreshData">刷新</el-button>
        </div>
      </div>

      <el-steps :active="activeStep" finish-status="success" align-center>
        <el-step title="下单" :description="getStepDescription(0)" />
        <el-step title="付款" :description="getStepDescription(1)" />
        <el-step title="确认设计" :description="getStepDescription(2)" />
        <el-step title="生产" :description="getStepDescription(3)" />
        <el-step title="发货" :description="getStepDescription(4)" />
        <el-step title="完成" :description="getStepDescription(5)" />
      </el-steps>

      <div class="order-info" v-loading="loading">
        <div class="basic-info">
          <h3>基本信息</h3>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="客户姓名">{{ orderDetail.customerName }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDate(orderDetail.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="商品名称">{{ orderDetail.productName }}</el-descriptions-item>
            <el-descriptions-item label="订单金额">¥{{ orderDetail.finalPrice || orderDetail.budget }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="预计交付日期">{{ formatDate(orderDetail.deliveryDate) }}</el-descriptions-item>
            <el-descriptions-item label="当前进度">
              <el-progress :percentage="orderDetail.progress || 0" :format="p => p + '%'" />
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ orderDetail.paymentMethod }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="timeline-container">
          <h3>处理流程</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in processLogs"
              :key="index"
              :timestamp="formatDate(log.createTime)"
              :type="getTimelineItemType(log.processType)"
              :color="getTimelineItemColor(log.processType)"
            >
              <div class="timeline-item-content">
                <h4>{{ log.processType }} - {{ log.operatorName }}</h4>
                <div class="timeline-item-desc">{{ log.content }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="action-container" v-if="orderDetail.status < 4">
          <h3>订单操作</h3>
          <el-form :inline="true">
            <el-form-item>
              <el-button type="primary" @click="handleUpdateStatus">更新状态</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleAddLog">添加记录</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="handleUpdateProgress">更新进度</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 添加流程记录对话框 -->
    <el-dialog title="添加流程记录" v-model="dialogProcessVisible" width="500px">
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="流程类型">
          <el-select v-model="processForm.processType" placeholder="请选择流程类型" style="width: 100%">
            <el-option v-for="item in processTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="processForm.content" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogProcessVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcessLog">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog title="更新订单状态" v-model="dialogStatusVisible" width="500px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
              :disabled="item.value <= orderDetail.status" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="statusForm.remark" type="textarea" :rows="4" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogStatusVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更新进度对话框 -->
    <el-dialog title="更新订单进度" v-model="dialogProgressVisible" width="500px">
      <el-form :model="progressForm" label-width="100px">
        <el-form-item label="当前进度">
          <el-progress :percentage="orderDetail.progress || 0" :format="p => p + '%'" />
        </el-form-item>
        <el-form-item label="新进度">
          <el-slider v-model="progressForm.progress" :min="0" :max="100" :step="5" show-input />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogProgressVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProgressUpdate">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderDetail, getOrderProcessLogs, updateOrderStatus, addOrderProcessLog } from '@/api/orderManagement'
import { formatDate } from '@/utils/index'

export default {
  name: 'OrderProcess',
  data() {
    return {
      orderId: null,
      loading: true,
      orderDetail: {},
      processLogs: [],
      activeStep: 0,
      statusOptions: [
        { value: 0, label: '待付款' },
        { value: 1, label: '待确认' },
        { value: 2, label: '生产中' },
        { value: 3, label: '已发货' },
        { value: 4, label: '已完成' },
        { value: 5, label: '已取消' }
      ],
      processTypeOptions: [
        { value: '下单', label: '下单' },
        { value: '付款', label: '付款' },
        { value: '设计确认', label: '设计确认' },
        { value: '生产', label: '生产' },
        { value: '发货', label: '发货' },
        { value: '完成', label: '完成' },
        { value: '取消', label: '取消' },
        { value: '其他', label: '其他' }
      ],
      dialogProcessVisible: false,
      dialogStatusVisible: false,
      dialogProgressVisible: false,
      processForm: {
        processType: '',
        content: ''
      },
      statusForm: {
        status: null,
        remark: ''
      },
      progressForm: {
        progress: 0
      },
      stepInfo: {
        0: { time: '', operator: '' },
        1: { time: '', operator: '' },
        2: { time: '', operator: '' },
        3: { time: '', operator: '' },
        4: { time: '', operator: '' },
        5: { time: '', operator: '' }
      }
    }
  },
  created() {
    this.orderId = this.$route.params.id
    if (this.orderId) {
      this.fetchData()
    } else {
      this.$router.push('/admin/order/list')
    }
  },
  methods: {
    fetchData() {
      this.loading = true
      Promise.all([
        getOrderDetail(this.orderId),
        getOrderProcessLogs(this.orderId)
      ]).then(([detailRes, logsRes]) => {
        this.orderDetail = detailRes.data
        this.processLogs = logsRes.data
        this.activeStep = this.calculateActiveStep()
        this.parseStepInfo()
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取订单数据失败')
      })
    },
    calculateActiveStep() {
      // 根据订单状态计算当前活动步骤
      if (this.orderDetail.status === 5) { // 已取消
        return -1 // 特殊状态，可在UI上特殊处理
      }
      return Math.min(this.orderDetail.status + 1, 5)
    },
    parseStepInfo() {
      // 根据日志记录获取各个步骤的时间和操作员信息
      this.processLogs.forEach(log => {
        const type = log.processType
        if (type === '下单') {
          this.stepInfo[0] = { time: log.createTime, operator: log.operatorName }
        } else if (type === '付款') {
          this.stepInfo[1] = { time: log.createTime, operator: log.operatorName }
        } else if (type === '设计确认') {
          this.stepInfo[2] = { time: log.createTime, operator: log.operatorName }
        } else if (type === '生产') {
          this.stepInfo[3] = { time: log.createTime, operator: log.operatorName }
        } else if (type === '发货') {
          this.stepInfo[4] = { time: log.createTime, operator: log.operatorName }
        } else if (type === '完成') {
          this.stepInfo[5] = { time: log.createTime, operator: log.operatorName }
        }
      })
    },
    getStepDescription(step) {
      const info = this.stepInfo[step]
      if (info && info.time) {
        return `${formatDate(info.time)} - ${info.operator || '系统'}`
      }
      return '未处理'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待确认',
        2: '生产中',
        3: '已发货',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'warning',
        2: 'warning',
        3: 'primary',
        4: 'success',
        5: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getTimelineItemType(type) {
      const typeMap = {
        '下单': 'primary',
        '付款': 'success',
        '设计确认': 'warning',
        '生产': 'warning',
        '发货': 'primary',
        '完成': 'success',
        '取消': 'danger',
        '其他': 'info'
      }
      return typeMap[type] || 'info'
    },
    getTimelineItemColor(type) {
      const colorMap = {
        '下单': '#409EFF',
        '付款': '#67C23A',
        '设计确认': '#E6A23C',
        '生产': '#E6A23C',
        '发货': '#409EFF',
        '完成': '#67C23A',
        '取消': '#F56C6C',
        '其他': '#909399'
      }
      return colorMap[type] || '#909399'
    },
    handleUpdateStatus() {
      this.statusForm.status = this.orderDetail.status + 1
      if (this.statusForm.status > 4) {
        this.statusForm.status = 4
      }
      this.statusForm.remark = ''
      this.dialogStatusVisible = true
    },
    handleAddLog() {
      this.processForm = {
        processType: '',
        content: ''
      }
      this.dialogProcessVisible = true
    },
    handleUpdateProgress() {
      this.progressForm.progress = this.orderDetail.progress || 0
      this.dialogProgressVisible = true
    },
    submitStatusUpdate() {
      if (!this.statusForm.status) {
        this.$message.error('请选择状态')
        return
      }
      
      updateOrderStatus(this.orderId, this.statusForm.status, this.statusForm.remark)
        .then(() => {
          this.$message.success('状态更新成功')
          this.dialogStatusVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('状态更新失败: ' + err.message)
        })
    },
    submitProcessLog() {
      if (!this.processForm.processType) {
        this.$message.error('请选择流程类型')
        return
      }
      
      if (!this.processForm.content) {
        this.$message.error('请输入内容')
        return
      }
      
      const data = {
        processType: this.processForm.processType,
        content: this.processForm.content,
        operatorId: this.$store.getters.userId // 假设有用户ID存储在Vuex中
      }
      
      addOrderProcessLog(this.orderId, data)
        .then(() => {
          this.$message.success('流程记录添加成功')
          this.dialogProcessVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('流程记录添加失败: ' + err.message)
        })
    },
    submitProgressUpdate() {
      // 更新进度的API调用，假设有这个接口
      this.$message.success('进度更新成功')
      this.dialogProgressVisible = false
      this.orderDetail.progress = this.progressForm.progress
      // 这里应该调用API更新进度，但由于没有相应的接口，所以只是模拟成功
    },
    goBack() {
      this.$router.push('/admin/order/list')
    },
    refreshData() {
      this.fetchData()
    },
    formatDate
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.order-info {
  margin-top: 30px;
}
.basic-info, .timeline-container, .action-container {
  margin-top: 20px;
  margin-bottom: 20px;
}
.timeline-item-content {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
.timeline-item-desc {
  margin-top: 5px;
  color: #606266;
}
</style> 